package com.isoftstone.project.system.controller;

import com.isoftstone.common.BusinessException;

import com.isoftstone.common.constant.Constants;
import com.isoftstone.common.utils.JsonUtil;
import com.isoftstone.framework.aop.OpLogAopController;
import com.isoftstone.framework.controller.BaseController;
import com.isoftstone.framework.domain.Page;
import com.isoftstone.framework.domain.PageData;
import com.isoftstone.framework.domain.Tidings;
import com.isoftstone.project.system.domain.SysMenu;
import com.isoftstone.project.system.service.ISysMenuService;
import com.isoftstone.project.system.service.ISysRoleMenuService;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class SysMenuController extends BaseController {
    @Autowired
    ISysMenuService sysMenuService;

    @Autowired
    ISysRoleMenuService sysRoleMenuService;

    @RequestMapping("/system/menu/menulist")
    public ModelAndView menulist() {
        return new ModelAndView("system/menu/menu_list");
    }

    @RequestMapping("/system/menu/getMenulistPage")
    @ResponseBody
    public Object getMenulistPage(Page page) {
        Tidings<List<SysMenu>> tidings = new Tidings<List<SysMenu>>();
        PageData pd = this.getPageData();
        page.setPd(pd);
        try {
            List<SysMenu> menuList = sysMenuService.getMenulistPage(page);
            tidings.setT(menuList);
            tidings.setTotalResult(page.getTotalResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(Constants.ERRORMSG);
        }
        return tidings;
    }

    @RequestMapping("/system/menu/saveUpdateSysMenu")
    @ResponseBody
    @OpLogAopController(module="菜单管理",methods="updateSysMenu",description="0")
    public Object updateSysMenu(@ModelAttribute("menu")SysMenu menu) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            if(menu.getMenuId() == null || "".equals(menu.getMenuId())){
                SysMenu sysMenu = sysMenuService.getMenuByPermission(menu.getPermission());
                request.setAttribute("description","添加菜单");
                if(sysMenu == null){
                    if(!StringUtils.isNotBlank(menu.getLeveled())){
                        menu.setLeveled("0");
                    }
                    menu.setMenuId(this.get32UUID());
                    sysMenuService.saveSysMenu(menu);
                    tidings.setStatus(Constants.SUCCESS);
                    tidings.setMsg("保存成功！");
                }else{
                    tidings.setStatus(Constants.ERROR);
                    tidings.setMsg("权限编码重复！");
                }
            }else{
                request.setAttribute("description","修改菜单");
                sysMenuService.updateSysMenu(menu);
                tidings.setStatus(Constants.SUCCESS);
                tidings.setMsg("修改成功！");
            }
        } catch (Exception e) {
            tidings.setStatus(Constants.ERROR);
            tidings.setMsg("修改失败！");
            e.printStackTrace();
        }
        return tidings;
    }

    @RequestMapping("/system/menu/deleteSysMenu")
    @ResponseBody
    @OpLogAopController(module="菜单管理",methods="deleteSysMenu",description="删除菜单")
    public Object deleteSysMenu(String menuId) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            List<SysMenu> parent = sysMenuService.getMenuByParentId(menuId);
            if(parent.isEmpty()){
                sysMenuService.deleteSysMenu(menuId);
                sysRoleMenuService.deleteRoleMenusByMenuId(menuId);
                tidings.setStatus(Constants.SUCCESS);
                tidings.setMsg("删除成功！");
            }else{
                tidings.setStatus(Constants.SUCCESS);
                tidings.setMsg("删除失败,请先删除下级菜单！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(Constants.ERRORMSG);
        }
        return tidings;
    }

    //保存角色菜单
    @RequestMapping("/system/menu/saveRoleMenus")
    @ResponseBody
    @OpLogAopController(module="角色管理",methods="saveRoleMenus",description="更新角色菜单权限")
    public Object saveRoleMenus(String roleId, String menuIds) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            sysRoleMenuService.saveRoleMenus(roleId,menuIds);
            tidings.setStatus(Constants.SUCCESS);
            tidings.setMsg("保存成功！");
        } catch (Exception e) {
            tidings.setStatus(Constants.SUCCESS);
            tidings.setMsg("保存失败！");
            e.printStackTrace();
        }
        return tidings;
    }

    @RequestMapping("/system/menu/saveRoleAppIds")
    @ResponseBody
    @OpLogAopController(module="角色管理",methods="saveRoleMenus",description="更新角色应用权限")
    public Object saveRoleAppIds(String roleId, String appIds) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            sysRoleMenuService.saveRoleAppIds(roleId,appIds);
            tidings.setStatus(Constants.SUCCESS);
            tidings.setMsg("保存成功！");
        } catch (Exception e) {
            tidings.setStatus(Constants.SUCCESS);
            tidings.setMsg("保存失败！");
            e.printStackTrace();
        }
        return tidings;
    }

    @RequestMapping("/system/menu/getMenuById")
    public ModelAndView getMenuById(String menuId) {
        ModelAndView md = new ModelAndView();
        try {
            SysMenu sysMenu = sysMenuService.getMenuById(menuId);
            md.addObject("sysMenu", sysMenu);
        } catch (Exception e) {
            e.printStackTrace();
        }
        md.setViewName("system/banner/banner_details");
        return md;
    }

    @RequestMapping("/system/menu/toMenuEdit")
    public ModelAndView toMenuEdit(String menuId) {
        ModelAndView md = new ModelAndView();
        try {
            List<SysMenu> menuList = sysMenuService.getMenuAll(null);	//获取所有菜单
            String json = JsonUtil.beanToJson(menuList);
            json = json.replaceAll("menuId", "id").replaceAll("parentId", "pId").replaceAll("menuName", "name");
            md.addObject("zTreeNodes",json);

            SysMenu sysMenu = sysMenuService.getMenuById(menuId);
            md.addObject("sysMenu", sysMenu);
        } catch (Exception e) {
            e.printStackTrace();
        }
        md.setViewName("system/menu/menu_edit");
        return md;
    }

    @RequestMapping("/system/menu/getMenuAll")
    @ResponseBody
    public Object getMenuAll() {
        Tidings<String> tidings = new Tidings<String>();
        try {
            List<SysMenu> menuList = sysMenuService.getMenuAll(null);
            String json = JsonUtil.beanToJson(menuList);
            json = json.replaceAll("menuId", "id").replaceAll("parentId", "pId").replaceAll("menuName", "name");
            tidings.setStatus(Constants.SUCCESS);
            tidings.setT(json);
        } catch (Exception e) {
            tidings.setStatus(Constants.SUCCESS);
            tidings.setMsg("数据异常！");
            e.printStackTrace();
        }
        return tidings;
    }


    /**
     * 显示菜单列表ztree(菜单授权菜单)
     * @param roleId 角色ID
     * @return
     */
    @RequestMapping(value="/system/menu/listmenus")
    public ModelAndView listAllMenu(String roleId)throws Exception{
        ModelAndView mv = this.getModelAndView();
        try{
            List<String> roleMenus = sysRoleMenuService.getMenusByRoleId(roleId);

            List<SysMenu> menuList = sysMenuService.getMenuAll(null);	//获取所有菜单

            menuList = this.readMenu(menuList, roleMenus);			//根据角色权限处理菜单权限状态(递归处理)

            String json = JsonUtil.beanToJson(menuList);
            json = json.replaceAll("menuId", "id").replaceAll("parentId", "pId").replaceAll("menuName", "name");
            mv.addObject("zTreeNodes",json);
            mv.addObject("roleId",roleId);
            mv.setViewName("system/role/menuqx");
        } catch(Exception e){
            e.printStackTrace();
        }
        return mv;
    }
    @RequestMapping("/system/menu/getMenuByAppId")
    @ResponseBody
    public Object getMenuByClientId(String appId) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            List<SysMenu> menuList = sysMenuService.getMenuAll(appId);
            String json = JsonUtil.beanToJson(menuList);
            json = json.replaceAll("menuId", "id").replaceAll("parentId", "pId").replaceAll("menuName", "name");
            tidings.setStatus(Constants.SUCCESS);
            tidings.setT(json);
        } catch (Exception e) {
            tidings.setStatus(Constants.SUCCESS);
            tidings.setMsg("数据异常！");
            e.printStackTrace();
        }
        return tidings;
    }
    /**
     * 查询header链接
     * @return
     */
    @RequestMapping("/system/menu/getMenuByUrl")
    @ResponseBody
    public Object getMenuByUrl() {
        Tidings<List<SysMenu>> tidings = new Tidings<List<SysMenu>>();
        try {
            List<SysMenu> menuList = null;
            if(this.getUser() !=null){
                menuList = sysMenuService.getMenuByUrl(this.getUser().getUserId());
            }else{
                menuList = sysMenuService.getMenuByUrl("");
            }
            tidings.setStatus(Constants.SUCCESS);
            tidings.setT(menuList);
        } catch (Exception e) {
            tidings.setStatus(Constants.SUCCESS);
            tidings.setMsg("数据异常！");
            e.printStackTrace();
        }
        return tidings;
    }

    public List<SysMenu> readMenu(List<SysMenu> menuList, List<String> list){
        List<String> str = new ArrayList<>();
        for(int i=0;i<menuList.size();i++){
            menuList.get(i).setChecked(list.contains(menuList.get(i).getMenuId()));
        }
        return menuList;
    }

}

